package models

import (
	"errors"
	"github.com/liangchao/blogo/src/common/global"
	"time"
)

type Tag struct {
	TagId int `gorm:"tag_id primaryKey" json:"tag_id"`
	TagName string `gorm:"tag_name" json:"tag_name"`
	IsDeleted int `gorm:"is_deleted" json:"is_deleted"`
	CreateTime *time.Time `gorm:"create_time" json:"create_time"`
	CreateTimeStr string `gorm:"-"`
}

func (*Tag) TableName() string{
	return "tb_blog_tag"
}

// GetTagNameById 根据 Id 查询标签名字
func (t *Tag) GetTagNameById() (err error) {
	if t.TagId < 1 {
		err = errors.New("not id < 1")
	}
	err = global.DB.Where("is_deleted = ?", 0).Where("tag_id = ?", t.TagId).Select("tag_name", "tag_id").Find(t).Error
	return
}

// GetAllTags 查询所有的 Tag
func (t *Tag) GetAllTags() (tags []Tag, err error) {
	err = global.DB.Table(t.TableName()).Where("is_deleted = ?", 0).Select("tag_name", "tag_id").Find(&tags).Error
	return
}


type BlogTagRelation struct {
	RelationId int `gorm:"relation_id primaryKey" json:"relation_id"`
	BlogId int `gorm:"blog_id" json:"blog_id"`
	TagId int `gorm:"tag_id" json:"tag_id"`
	IsDeleted int `grom:"is_deleted" json:"is_deleted"`
	CreateTime *time.Time `gorm:"create_time", json:"create_time"`
	CreateTimeStr string `gorm:"-"`
}

func (*BlogTagRelation) TableName() string {
	return "tb_blog_tag_relation"
}

// GetTagIdsByBlogId 通过 blogId 查询到所属的 tagIds
func (r *BlogTagRelation) GetTagIdsByBlogId() (tagIds []BlogTagRelation, err error) {
	if r.BlogId < 1 {
		err = errors.New("not id < 1")
		return
	}
	err = global.DB.Table(r.TableName()).Where("is_deleted = ?", 0).Where("blog_id = ?", r.BlogId).Select("tag_id").Find(&tagIds).Error
	return
}



